(ns userdict
  (:use [util.contrib.java-utils :only [read-properties get-system-property]])
  (:use util.utils))


(def ^:dynamic *user-property-file* "mekit-user.properties")
(def ^:dynamic *user-script-file* "mekit-user.clj")
(def ^:dynamic *user-script-ns* 'mekit-user)

(defn get-user-properties []
  (when-let [file (get-resource *user-property-file*)]
    (into {} (read-properties file))))


(defn get-user-property [key]
  (or (get (get-user-properties) key) (get-system-property key) (System/getenv key)))

(defn load-user-script []
  (when-let [file (get-resource *user-script-file*)]
    (let [ns (create-ns *user-script-ns*)]
      (binding [*ns* ns]
        (clojure.core/refer-clojure)
        (load-file file))
      (ns-interns ns))))

(def get-user-vars (memoize load-user-script))

(defn get-user-var [key]
  (if (symbol? key)
    (when-let [v (get (get-user-vars) key)] (var-get v))
    (get-user-var (symbol key))))

(defn load-user-vars [] ; TODO: load vars to current ns
  (let [vars (get-user-vars)]
    (refer (ns-name *ns*))))

(defn uvar
  ([k]
    (or (get-user-var k) (get-user-property k)))
  ([k v]
    (or (uvar k) v)))

(defn uvar! [k]
  (or (get-user-var k) (get-user-property k) (throw (Exception. (str "Can't find user property " k)))))

(defmacro defuservar
  ([k v]
    `(def ~k (uvar ~(name k) ~v)))
  ([k]
    `(def ~k (uvar ~(name k)))))

(defmacro defuservar! [k]
  `(def ~k (uvar! ~(name k))))

